//
//  TreeHoleVideoPlayViewController.m
//  togetherPlay
//
//  Created by coder on 2018/12/21.
//  Copyright © 2018 stoneobs.qq.com. All rights reserved.
//

#import "STTools_VideoPlayViewController.h"
#import "STTools_PlayControlView.h"
@interface STTools_VideoPlayViewController ()

@property(nonatomic, strong) ZFPlayerController                     *player;/**<  */
@property (nonatomic, strong) ZFPlayerControlView                  *controlView;
@property(nonatomic, strong) UIView                                *fatherView;/**<  */


@property(nonatomic, strong) ZFPlayerController                     *below_layer;/**<  */
@property (nonatomic, strong) ZFPlayerControlView                  *below_controlView;
@property(nonatomic, strong) UIView                                *below_fatherView;/**<  */


@property(nonatomic, strong) UIImageView                     *imageView;/**<  */
@property(nonatomic, strong) AVURLAsset                     *asset;/**<  */
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@end

@implementation STTools_VideoPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.hidden = YES;
    [self stoneobs_ui_configSubView];
    self.dataSouce = NSMutableArray.new;
    // Do any additional setup after loading the view.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self stoneobs_fun_generateFrames];
}
#pragma mark --subView
- (void)stoneobs_ui_configSubView{
    self.view.backgroundColor = UIColor.blackColor;
    self.tableView.backgroundColor = UIColor.clearColor;
    self.view.backgroundColor = UIColor.blackColor;
    self.tableView.contentInset = UIEdgeInsetsZero;
    

    
    ({
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
        [imageView sd_setImageWithURL:self.img_url.stoneobs_fun_st_safeImageUrl];
        [self.view insertSubview:imageView atIndex:0];
        self.imageView = imageView;
        imageView.userInteractionEnabled = NO;
        UIVisualEffectView * visouView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
        visouView.frame = imageView.bounds;
        [self.view addSubview:visouView];
        
//        self.below_fatherView = self.imageView;
//        self.below_fatherView.backgroundColor = UIColor.blackColor;
//         ZFAVPlayerManager * avmanger =  ZFAVPlayerManager.new;
//        self.below_layer = [ZFPlayerController playerWithPlayerManager:avmanger containerView:self.below_fatherView];
//        self.below_layer.assetURL = [NSURL URLWithString:self.url];
//        self.below_layer.pauseWhenAppResignActive = YES;
//        self.below_layer.controlView = self.below_controlView;
//        self.below_layer.currentPlayerManager.muted = YES;
    });
     
    ({
           // 初始化
           UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, STONEOBS_UI_UISCREEN_WIDTH, STONEOBS_UI_UISCREEN_HEIGHT)];
           self.fatherView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, STONEOBS_UI_UISCREEN_WIDTH, STONEOBS_UI_UISCREEN_WIDTH)];
           self.fatherView.backgroundColor = UIColor.blackColor;                                                                                        self.fatherView.centerY = header.height/2;
           [header addSubview:self.fatherView];
            ZFAVPlayerManager * avmanger =  ZFAVPlayerManager.new;
           self.player = [ZFPlayerController playerWithPlayerManager:avmanger containerView:self.fatherView];
           self.player.assetURL = [NSURL URLWithString:self.url];
           self.player.pauseWhenAppResignActive = YES;
           self.player.controlView = self.controlView;
        
           [self.view addSubview:header];
           __weak typeof(self) weakSelf =  self;
           [self.player.currentPlayerManager setPlayerPlayTimeChanged:^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
               
               NSLog(@"currentTime = %f,duration = %f",currentTime,duration);
           }];
            [self.player.currentPlayerManager setPlayerPlayStateChanged:^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerPlaybackState playState) {

            
            }];
    });
   

   
}
- (void)stoneobs_fun_changeImage{
    self.imageView.image = [self stoneobs_fun_thumbnailImageAtCurrentTime];
}
- (UIImage *)stoneobs_fun_thumbnailImageAtCurrentTime {
    
    @autoreleasepool {
        if (!self.asset) {
          AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:self.url] options:nil];
            self.asset = asset;
        }
        
        ZFAVPlayerManager * avmanger =  (id)self.player.currentPlayerManager;
        AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:self.asset];
        CMTime expectedTime = avmanger.playerItem.currentTime;
        CGImageRef cgImage = NULL;
        
        imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
        imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
        cgImage = [imageGenerator copyCGImageAtTime:expectedTime actualTime:NULL error:NULL];
        
        if (!cgImage) {
            imageGenerator.requestedTimeToleranceBefore = kCMTimePositiveInfinity;
            imageGenerator.requestedTimeToleranceAfter = kCMTimePositiveInfinity;
            cgImage = [imageGenerator copyCGImageAtTime:expectedTime actualTime:NULL error:NULL];
        }
        
        UIImage *image = [UIImage imageWithCGImage:cgImage];
        return image;
    }

}
-(void)stoneobs_fun_generateFrames{
    NSURL * nsUrl=[NSURL URLWithString:self.url];
    AVAsset * avAsset=[AVAsset assetWithURL:nsUrl];
    //视频总秒数
    CMTime cmTime = avAsset.duration;
    NSTimeInterval timeInterVal=CMTimeGetSeconds(cmTime);
    int secend = timeInterVal;
    secend = secend % 60;
    //一秒取一帧
    NSMutableArray * specifiedTimes=[NSMutableArray array];
    for (int i = 1; i <= secend ; i++) {
        CMTime timeFrame = CMTimeMake(i, 1);
        NSValue *timeValue = [NSValue valueWithCMTime:timeFrame];
        [specifiedTimes addObject:timeValue];
    }
    //定义图片生成器
    AVAssetImageGenerator * generator=[AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
    //开始异步取帧
    __weak __typeof(self) weakSelf=self;
    [generator generateCGImagesAsynchronouslyForTimes:specifiedTimes completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        NSLog(@"requestedTime-----: (%lld,%d)", requestedTime.value,requestedTime.timescale);
        NSLog(@"actualTime-----: (%lld,%d)", actualTime.value,actualTime.timescale);
        

        switch (result) {
            case AVAssetImageGeneratorCancelled:
                NSLog(@"Cancelled");
                break;
            case AVAssetImageGeneratorFailed:
                NSLog(@"Failed");
                break;
            case AVAssetImageGeneratorSucceeded: {
                UIImage * frameImg = [UIImage imageWithCGImage:image];
                [self.dataSouce addObject:frameImg];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    NSArray * array = self.dataSouce;
                    NSLog(@"%@",array);
                });
                
            }
                break;
        }
        
    }];
}
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = YES;
        
    }
    return _controlView;
}
- (ZFPlayerControlView *)below_controlView {
    if (!_below_controlView) {
        _below_controlView = [ZFPlayerControlView new];
        _below_controlView.fastViewAnimated = YES;
        _below_controlView.autoHiddenTimeInterval = 5;
        _below_controlView.autoFadeTimeInterval = 0.5;
        _below_controlView.prepareShowLoading = YES;
        _below_controlView.prepareShowControlView = YES;
        
    }
    return _controlView;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

}

@end
